/**
 * @fileoverview Giant Interective Group, Inc. Javascript Library v#version.
 * 该Javascript UI库是基于jQuery的扩展。
 * <pre>
 * Copyright (C) 2004-2009 Giant Interective Group, Inc. All rights reserved.
 * 版权所有 2004-2009 上海巨人网络科技有限公司
 * </pre>
 * 
 * @version #version, #date
 * @author  Songlu
 */

if(typeof giant === 'undefined')
    var giant = {};

if(typeof giant.ui === 'undefined')
	giant.ui = {};

(function($) {
	var calendarProperties = {
		solarMonth: [31,28,31,30,31,30,31,31,30,31,30,31],
		charStr1: ['日','一','二','三','四','五','六'],
		charStr2: ['年','月','日','星期']
	}
	/**
	 * 创建一个新的日历控件。
	 * 
	 * @class giant.ui.Calendar。Giant UI 的Calendar控件。
	 * @example
	 * <pre>
	 * // 将下面代码放入到body体内尾部
	 * &lt;div id="__calendar" style="display:none;"&gt;
	 * 		&lt;div id="__c_solar" style="float:left; font-weight:bold;"&gt;&lt;/div&gt;
	 * 		
	 *		&lt;table id="__c_solar_month" cellspacing="1" cellpadding="0"&gt;
	 *			&lt;thead&gt;
	 *				&lt;tr&gt;&lt;td&gt;日&lt;/td&gt;&lt;td&gt;一&lt;/td&gt;&lt;td&gt;二&lt;/td&gt;&lt;td&gt;三&lt;/td&gt;&lt;td&gt;四&lt;/td&gt;&lt;td&gt;五&lt;/td&gt;&lt;td&gt;六&lt;/td&gt;&lt;/tr&gt;
	 *			&lt;/thead&gt;
	 *			&lt;tbody&gt;
	 *			&lt;script language="javascript"&gt;
	 *			                                                                                                    
	 *		            var num                                                                                                    
	 *		            for(i=0;i&lt;6;i++) {                                                                                                    
	 *		               document.write('&lt;tr align=center&gt;')                                                                                                    
	 *		               for(j=0;j&lt;7;j++) {                                                                                                    
	 *		                  num = i*7+j;                                                                                                    
	 *		                  document.write('&lt;td id="__c_date_' + num +'"&gt;&lt;span id="__c_sDate_' + num +'" style="font-family:Arial Black;font-size:20px;')                                                                                                    
	 *		                  if(j == 0) document.write(' color:red')                                                                                                    
	 *		                  if(j == 6)                                                                                                    
	 *		                     if(i%2==1) document.write(' color:red;')                                                                                                    
	 *		                        else document.write(' color:red;')                                                                                                    
	 *		                  document.write('" title=""&gt;0&lt;/span&gt;&lt;/td&gt;')                                                                                                    
	 *		               }                                                                                                    
	 *		               document.write('&lt;/tr&gt;')                                                                                                    
	 *		            }                                                                                                    
	 *				
	 *				&lt;/script&gt;
	 *				&lt;/tbody&gt;
	 *			&lt;/table&gt;
	 *			
	 *			&lt;div style="float:left;"&gt;
	 *				&lt;select id="__c_select_y"&gt;
	 *				&lt;script language=JavaScript&gt;
	 *				for(i=1900;i&lt;2050;i++) document.write('&lt;option&gt;'+i)   
	 *				&lt;/script&gt;
	 *				&lt;/select&gt;年
	 *				&lt;select id="__c_select_m"&gt;
	 *				&lt;script language=JavaScript&gt;
	 *				for(i=1;i&lt;13;i++) document.write('&lt;option&gt;'+i)   
	 *				&lt;/script&gt;
	 *				&lt;/select&gt;月
	 *			&lt;/div&gt;
	 *			&lt;div style="float:right;text-align:center;"&gt;
	 *				&lt;a href="javascript:void(0);" id="__c_btn_prev_y"&gt;上一年&lt;/a&gt;
	 *				&lt;a href="javascript:void(0);" id="__c_btn_prev_m"&gt;上一月&lt;/a&gt;
	 *				&lt;a href="javascript:void(0);" id="__c_btn_next_m"&gt;下一月&lt;/a&gt;
	 *				&lt;a href="javascript:void(0);" id="__c_btn_next_y"&gt;下一年&lt;/a&gt;
	 *			&lt;/div&gt;
	 * &lt;/div&gt;
	 * &ltscript type="text/javascript"&gt
	 * $(document).ready(function(){
	 * 		var options = {
	 * 			//start、end为要操作的文本框ID，必选，最多两项。
	 * 			txts: [['#start', '#end'],['#simple'],['#simple2']]
	 * 		}
	 * 		var calendar = new giant.ui.Calendar(options);
	 * 			
	 * });
	 * &lt/script&gt
	 * </pre>
	 * @constructor
	 * @param {Object} configs 按钮的属性集。
	 */
	giant.ui.Calendar = function(configs){
		this.initCalendar(configs);	
	};

	/**
	 * 计算指定月的天数(公历)。
	 * @param {Number} year 要计算的年份。
	 * @param {Number} month 要计算的月份。
	 * @returns {Number} 返回指定月的天数。
	 */
	giant.ui.Calendar.solarMonthDays = function(year, month){
		if(month==1)
			return(((year%4 == 0) && (year%100 != 0) || (year%400 == 0))? 29: 28);
		else
			return(calendarProperties.solarMonth[month]);
	}

/**#@+
 * @memberOf giant.ui.Calendar
 * @method
 */
giant.ui.Calendar.prototype = {
	/** 日历控件初始化。
     * @private
     */
	initCalendar: function(options){
		$this = this;
		var date = new Date();
		
		options.tYear = date.getFullYear();
		options.tMonth = date.getMonth();
		options.tDay = date.getDate();
		
		
		options.cYear = options.tYear;
		options.cMonth = options.tMonth;
		options.cDay = options.tDay;
		
		options.objCalendar = null;
		
		this._generateCalendar(options);
	},
    _generateCalendar: function(options) {

        options.elmCalendar = $('#__calendar');
       	options.elmSolar = $('#__c_solar');
		options.elmSolarMonth = $('#__c_solar_month');
		options.elmBtnPrevYear = $('#__c_btn_prev_y');
		options.elmBtnPrevMonth = $('#__c_btn_prev_m');
		options.elmBtnNextYear = $('#__c_btn_next_y');
		options.elmBtnNextMonth = $('#__c_btn_next_m');
		options.elmSelectYear = $('#__c_select_y');
		options.elmSelectMonth = $('#__c_select_m');
		options.elmTxts = [];
		
		$.each(options.txts, function(index, itm){
			options.elmTxts[index] = [];
			$.each(itm, function(_index, _itm){
				var item = $(_itm);
				options.elmTxts[index][_index] = {};
				options.elmTxts[index][_index].index = _index;
				options.elmTxts[index][_index].date = null;
				options.elmTxts[index][_index].elm = item[0];
				item.bind('click', function(){
					options.activeTxtIndex1 = index;
					options.activeTxtIndex2 = _index;
				});
				//判断浏览器
				if(giant.B.msie){
					item[0].attachEvent("onpropertychange",function(event){
						if(item.val().trim() == '' ){
							options.elmTxts[activeTxtIndex1][activeTxtIndex2].date = null;
						}
					})
				} else {
					item[0].addEventListener("input",function(event){
						if(item.val().trim() == '' ){
							options.elmTxts[activeTxtIndex1][activeTxtIndex2].date = null;
						}
					},false);
				}
			})
			
		});
		options.elmBtnPrevYear[0]['onclick'] = this.previousYear(options);
		options.elmBtnPrevMonth[0]['onclick'] = this.previousMonth(options);
		options.elmBtnNextYear[0]['onclick'] = this.nextYear(options);
		options.elmBtnNextMonth[0]['onclick'] = this.nextMonth(options);
		options.elmSelectYear[0]['onchange'] = this.lookup(options);
		options.elmSelectMonth[0]['onchange'] = this.lookup(options);
		$(document).bind('click',function(event){
			var target = event.target || window.event.srcElement;
			var temp = false;
			var index1 = 0;
			var index2 = 0;
//			for(var i=0; i< options.elmTxts.length; i++){
//				for(var j=0; j<options.elmTxts[i].length; j++){
//					if($(options.elmTxts[i][j])[0] == target){
//						temp = true;
//						index1=i;
//						index2=j;
//						break;
//					}
//				}
//				
//			}
			$.each(options.elmTxts, function(index, itm){
				$.each(itm, function(_index, _itm){
//					var item = $(_itm);
//					options.elmTxts[index][_index] = {};
//					options.elmTxts[index][_index].index = index;
//					options.elmTxts[index][_index].date = null;
//					options.elmTxts[index][_index].elm = itm[0];
//					item.bind('click', function(){
//						options.activeTxtIndex1 = index;
//						options.activeTxtIndex2 = _index;
//					});
					if(options.elmTxts[index][_index].elm == target){
						temp = true;
						index1 = index;
						index2 = _index;
						return;
					}
				});
				if(temp) return;
			});
			
			if(temp){
				if(options.elmTxts[options.activeTxtIndex1][0].date == null && options.activeTxtIndex2 != 0){
					options.elmCalendar.hide();
					alert('请先输入起始的日期');
					options.elmTxts[options.activeTxtIndex1][0].elm.focus();
					return;
				}
				var left = (event.clientX + options.elmCalendar.width() > $(document).width())?(event.clientX - options.elmCalendar.width()):event.clientX;
				var top = (event.clientY + options.elmCalendar.height() > $(document).height())?(event.clientY - options.elmCalendar.height()):event.clientY;
				options.elmCalendar.css({'left':left+'px','top':event.clientY+'px'})
				if(options.elmTxts[options.activeTxtIndex1][options.activeTxtIndex2].elm.value != null && options.elmTxts[options.activeTxtIndex1][options.activeTxtIndex2].elm.value != '') {
					var str = options.elmTxts[options.activeTxtIndex1][options.activeTxtIndex2].elm.value;
					var date = str.split('-');
					options.cYear = date[0];
					options.cMonth = date[1]-1;
					options.cDay = date[2];
					$this.build(options.cYear,options.cMonth, options.cDay, options);
					$this.updateSolar(options.cYear,options.cMonth, options.cDay, options);
				}else{
					$this.build(options.tYear, options.tMonth, options.tDay, options);
					$this.updateSolar(options.tYear, options.tMonth, options.tDay, options);
				}
				
				options.elmCalendar.show();
			}
			if(!temp){
				var tempTarget = target;
				var tmp = false;
				while(tempTarget.parentNode != null){
					if(options.elmCalendar[0] == tempTarget){
						tmp = true;
						break;
					}
					tempTarget = tempTarget.parentNode;
				}
				if(!tmp){
					options.elmCalendar.hide();
				}
			}
		});
    },
	/**
	 * 依据指定年份月份构建日历。
	 * @param {Number} year 公历年份。
	 * @param {Number} month 公历月份。
	 */
	build: function(year, month, day, options){
		//_test1 = new Date(); 测试时间
		options.calElements = [];

		options.solarMonthDays = giant.ui.Calendar.solarMonthDays(year,month);
		options.firstWeek = new Date(year,month,1).getDay();

		for(var i=0;i<options.solarMonthDays;i++) {
			options.calElements[i] = {};
			options.calElements[i].sYear = year;
			options.calElements[i].sMonth = month;
			options.calElements[i].sDay = i+1;
			options.calElements[i].week = calendarProperties.charStr1[(i+options.firstWeek)%7];
		}
		
//		//今日
//		if(year==options.tYear && month==options.tMonth) {
//			options.calElements[options.tDay-1].isToday = true;
//		}
//		//当前日
//		if(year==options.cYear && month==options.cMonth && options.cDay <= options.calElements.length) {
//			options.calElements[options.cDay-1].isCDay = true;
//		}
		
		this.update(year, month, day, options);
		
	},
	/**
	 * 更新公历显示信息。
	 * @param {Number} year 公历年份。
	 * @param {Number} month 公历月份。
	 * @param {Number} date 公历日份。
	 */
	updateSolar: function(year, month, day, options){
		options.elmSolar.html('公历:' + 
							year + calendarProperties.charStr2[0] + 
							(((month+1)<10)?'0' + (month+1):(month+1)) + calendarProperties.charStr2[1] + 
							(day<10?'0'+day:day) + calendarProperties.charStr2[2] + '&nbsp;&nbsp;' + 
							calendarProperties.charStr2[3] + calendarProperties.charStr1[new Date(year, month, day).getDay()]);
	},
	/**
	 * 更新月历显示信息。
	 * @param {Number} year 公历年份。
	 * @param {Number} month 公历月份。
	 */
	update: function(year, month, day, options){
		
		for(i=0;i<42;i++) {
			
			var sObj=$('#__c_sDate_'+ i);
			var dOfferset = i - options.firstWeek;
			
//			sObj.parent().removeClass('today');
//			sObj.parent().removeClass('current');
			sObj.parent().css({'cursor':'default'});
//			sObj.parent().unbind('mouseover');
//			sObj.parent().unbind('mouseout');
			if(dOfferset>-1 && dOfferset<options.solarMonthDays) {
				sObj.html(dOfferset+1);
//				sObj.parent().bind('mouseover', function(event){
//					$(this).addClass('hover');
//				});
//				sObj.parent().bind('mouseout', function(event){
//					$(this).removeClass('hover');
//				})
				sObj.parent().css({'cursor':'pointer'});
//				if(options.calElements[dOfferset].isToday) {
//					sObj.parent().addClass('today');
//				}
//				if(options.calElements[dOfferset].isCDay) {
//					sObj.parent().addClass('current');
//				}
				sObj.parent()[0]['onclick'] = this.setDate(dOfferset, options);
			} else { //非日期
				sObj.html('&nbsp;');
			}
		}
		
		//_test2 = new Date(); 测试时间
		//alert(_test2 - _test1); 测试时间
	},
	/** 回调函数 */
	callback: function(index){
		$this = this;
		return function(event){
		}
	},
	/** 对文本框进行赋值 */
	setDate: function(dOfferset, options){
		var $this = this;
		return function(event){
			var cal = options.calElements[dOfferset];
			var txt = options.elmTxts[options.activeTxtIndex1][options.activeTxtIndex2].elm;
			if(options.elmTxts[options.activeTxtIndex1].length > 1){
				var tempDate = new Date(cal.sYear, cal.sMonth, cal.sDay);
				if(options.activeTxtIndex2 == 0){
					if( options.elmTxts[options.activeTxtIndex1][1].date != null){
						if(tempDate - options.elmTxts[options.activeTxtIndex1][1].date > 0){
							alert('选择的日期不能晚于后面的日期！请重新选择。。。');
							return;
						}
					}
				}else{
					if( options.elmTxts[options.activeTxtIndex1][0].date != null){
						if(tempDate - options.elmTxts[options.activeTxtIndex1][0].date < 0){
							alert('选择的日期不能早于前面的日期！请重新选择。。。');
							return;
						}
					}
				}
				
				options.elmTxts[options.activeTxtIndex1][options.activeTxtIndex2].date = tempDate;
			}
			
			txt.value = cal.sYear + '-' + ((cal.sMonth + 1)<10?'0' + (cal.sMonth + 1):cal.sMonth + 1) + '-' + ((cal.sDay<10)?'0'+cal.sDay:cal.sDay);
			options.elmCalendar.hide();
		}
	},
	/** 上一年 */
	previousYear: function(options){
		var $this = this;
		return function(event){
			if(options.cYear > 1901){
				--options.cYear;
				$this.build(options.cYear, options.cMonth, options.cDay, options);
				$this.updateSolar(options.cYear, options.cMonth, options.cDay, options);
			}
		}
	},
	/** 下一年 */
	nextYear: function(options){
		var $this = this;
		return function(event){
			if(options.cYear < 2049){
				++options.cYear;
				$this.build(options.cYear, options.cMonth, options.cDay, options);
				$this.updateSolar(options.cYear, options.cMonth, options.cDay, options);
			}
		}
	},
	/** 上一月 */
	previousMonth: function(options){
		var $this = this;
		return function(event){
			if(options.cMonth > 0) {
				$this.build(options.cYear, --options.cMonth, options.cDay, options);
				$this.updateSolar(options.cYear, options.cMonth, options.cDay, options);
			} else if(options.cYear > 1901) {
				options.cMonth = 11;
				--options.cYear;
				$this.build(options.cYear, options.cMonth, options.cDay, options);
				$this.updateSolar(options.cYear, options.cMonth, options.cDay, options);
			}
		}
	},
	/** 下一月 */
	nextMonth: function(options){
		var $this = this;
		return function(event){
			if(options.cMonth < 11) {
				$this.build(options.cYear, ++options.cMonth, options.cDay, options);
				$this.updateSolar(options.cYear, options.cMonth, options.cDay, options);
			} else if(options.cYear < 2049) {
				options.cMonth = 0;
				++options.cYear
				$this.build(options.cYear, options.cMonth, options.cDay, options);
				$this.updateSolar(options.cYear, options.cMonth, options.cDay, options);
			}
		}
	},
	/** 通过下拉列表进行日期跳转 */
	lookup: function(options){
		$this = this;
		return function(event){
			options.cYear = Number(options.elmSelectYear[0][options.elmSelectYear[0].selectedIndex].innerHTML);
			options.cMonth = options.elmSelectMonth[0].selectedIndex
			$this.build(options.cYear , options.cMonth, options.cDay, options);
			$this.updateSolar(options.cYear, options.cMonth, options.cDay, options);
		}
	}
}
/**#@-*/

})(jQuery);
